<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;

/**
 * 老师评价管理
 *
 * @icon fa fa-star
 */
class Teacherevaluation extends Backend
{
    /**
     * TeacherEvaluation模型对象
     * @var \app\admin\model\TeacherEvaluation
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('TeacherEvaluation');
    }

    /**
     * 查看评价列表
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            // 获取teacher_id参数
            $teacher_id = $this->request->get('teacher_id');
            
            // 获取城市和学校筛选参数
            $city_id = $this->request->get('city_id');
            $school_id = $this->request->get('school_id');
            
            $list = $this->model
                ->with(['student', 'teacher'])
                ->where(function($query) use ($where, $teacher_id, $city_id, $school_id) {
                    // 应用原有的$where条件
                    if (is_array($where)) {
                        foreach ($where as $field => $value) {
                            if (is_array($value)) {
                                $query->where($field, $value[0], $value[1]);
                            } else {
                                $query->where($field, $value);
                            }
                        }
                    } else if ($where instanceof \Closure) {
                        $where($query);
                    }
                    
                    // 特别处理teacher_id条件
                    if ($teacher_id) {
                        $query->where('teacher_id', $teacher_id);
                    }
                    
                    // 添加城市筛选条件
                    if ($city_id) {
                        $query->where('city_id', $city_id);
                    }
                    
                    // 添加学校筛选条件
                    if ($school_id) {
                        $query->where('school_id', $school_id);
                    }
                })
                ->order($sort, $order)
                ->paginate($limit);
            $total=$list->total();
            foreach ($list as $row) {
                // 检查student关联是否存在
                if ($row->getRelation('student')) {
                    $row->getRelation('student')->visible(['id', 'username', 'nickname']);
                }
                // 检查teacher关联是否存在
                if ($row->getRelation('teacher')) {
                    $row->getRelation('teacher')->visible(['id', 'username', 'nickname']);
                }
                // 检查class关联是否存在
                if ($row->getRelation('class')) {
                    $row->getRelation('class')->visible(['id', 'name']);
                }
            }
            $list = collection($list->items())->toArray();
            for($i=0;$i<count($list);$i++){
                $list[$i]['city_id']=model("Cityarea")->getCity_idTextAttr($list[$i]['city_id'],$list[$i]);
                $list[$i]['school_id']=model("School")->getSchool_idTextAttr($list[$i]['school_id'],$list[$i]);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加评价
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 自动插入session中的城市和学校ID
                if (isset($_SESSION['think']['admin']['city_id'])) {
                    $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                }
                if (isset($_SESSION['think']['admin']['school_id'])) {
                    $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑评价
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 自动插入session中的城市和学校ID
                if (isset($_SESSION['think']['admin']['city_id'])) {
                    $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                }
                if (isset($_SESSION['think']['admin']['school_id'])) {
                    $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除评价
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__("No rows were deleted"));
            }
        }
        $this->error(__("Parameter %s can not be empty", 'ids'));
    }
}